package StudyCode.summary.mycollection;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class ConvertMapStringObjectToString {
	public static String convertToString(
			java.util.Map<String, Object> properties) {
		java.util.List<String> parts = new java.util.ArrayList<String>();
		for (String key : properties.keySet()) {
			Object value = properties.get(key);
			if (value instanceof String) {
				parts.add(encode('=', new String[]{key, (String) value}));
			} else {
				throw new RuntimeException("Can't encode " + value);
			}
		}
		return encode(';', parts);
	}

	public static String encode(char delimiter, String[] parts) {
		java.util.List<String> partList = new java.util.ArrayList<String>();
		for (String part : parts) {
			partList.add(part);
		}
		return encode(delimiter, partList);
	}

	public static String encode(char delimiter, Iterable<String> parts) {
		StringBuilder result = new StringBuilder();
		for (String part : parts) {
			String encodedPart = part.replace("\\", "\\\\");
			encodedPart = encodedPart.replace("" + delimiter, "\\"
					+ delimiter);
			result.append(encodedPart);
			result.append(delimiter);
		}
		return result.toString();
	}
}
